package service

import (
	"context"
	"fmt"
	"jk-time/webook/internal/repository"
	"jk-time/webook/internal/service/sms"
	"math/rand"
)

var (
	ErrCodeSendTooMany   = repository.ErrCodeSendTooMany
	ErrCodeVerifyTooMany = repository.ErrCodeVerifyTooMany
)

type CodeService interface {
	Send(ctx context.Context, phone string, biz string) error
	Varify(ctx context.Context, biz, code, phone string) (bool, error)
}
type codeService struct {
	repo repository.CodeRepository
	sms  sms.Service
}

func NewCodeService(repo repository.CodeRepository, sms sms.Service) CodeService {
	return &codeService{repo: repo, sms: sms}
}

// Send 发验证码
func (svc *codeService) Send(ctx context.Context, phone string,
	//区别业务场景
	biz string) error {
	code := svc.generateCode()
	//放置redis,是否放置成功
	if err := svc.repo.Set(ctx, biz, phone, code); err != nil {
		return err
	}

	//发送验证码：腾讯、阿里云
	const codeTplId = ""
	return svc.sms.Send(ctx, codeTplId, []string{code}, phone)
}
func (svc *codeService) Varify(ctx context.Context, biz, code, phone string) (bool, error) {
	ok, err := svc.repo.Verify(ctx, biz, phone, code)
	if err == repository.ErrCodeVerifyTooMany {
		// 相当于，我们对外面屏蔽了验证次数过多的错误，我们就是告诉调用者，你这个不对
		return false, nil
	}
	return ok, err
}
func (svc *codeService) generateCode() string {
	num := rand.Intn(1000000)
	return fmt.Sprintf("%6d", num)
}
